package com.shundr.auth.activity;

import java.io.File;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.Timer;
import java.util.TimerTask;

import android.content.Intent;
import android.graphics.Bitmap;
import android.net.Uri;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.provider.MediaStore;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.TextView;

import com.actionbarsherlock.view.Menu;
import com.actionbarsherlock.view.MenuItem;
import com.nostra13.universalimageloader.core.ImageLoader;
import com.shundr.auth.channel.R;
import com.shundr.auth.base.BaseActivity;
import com.shundr.auth.common.model.AreaInfo;
import com.shundr.auth.common.util.AllCapTransfMethod;
import com.shundr.auth.common.util.AttrUtil;
import com.shundr.auth.common.util.Base64Util;
import com.shundr.auth.common.util.DateUtils;
import com.shundr.auth.common.util.LImageLoader;
import com.shundr.auth.common.util.PictureUtil;
import com.shundr.auth.common.util.ProgressDialogHelper;
import com.shundr.auth.common.view.DialogChoiceLength;
import com.shundr.auth.common.view.DialogChoiceTruckInfo;
import com.shundr.auth.frame.db.model.PictureInfo;
import com.shundr.auth.frame.util.JsonUtil;
import com.shundr.auth.frame.util.StringUtil;
import com.shundr.auth.frame.http.*;
import com.shundr.auth.frame.util.ToastHelper;
import com.shundr.auth.user.dao.TruckDao;
import com.shundr.auth.user.model.AttributeInfo;
import com.shundr.truck.http.UserTruckRequest;
import com.shundr.truck.model.TruckInfo;

/**
 * 添加车辆 AddTruckActivity
 * 
 * @author larry 2015-4-27 下午2:30:31
 * @version 1.0.0
 *
 */
public class AddSocialTruckActivity extends BaseActivity implements
		OnClickListener {

	private Button btnPCode;// 省份代号
	private EditText etTruckNum;// 车牌号码
	private Button btnTruckType;// 车辆类型
	private EditText etTruckLoad;// 载重
	private Button btnTruckLength;// 长度
	private EditText etTruckPhone;// 車輛電話

	private Button btnDirect;// 流向

	private Button btnSave;// 保存

	private String pType;// 车辆类型

	private ImageView ivFull;// 车辆照片

	private TextView tvTruckPicSample;// 车辆照片示例

	private PictureInfo mPTruckInfo;// 车辆照片

	private List<PictureInfo> mPictures = new ArrayList<PictureInfo>();
	private int flag = 0;

	private TruckDao truckDao = new TruckDao();

	public static final int NONE = 0;
	public static final int PHOTOHRAPH = 1;// 拍照
	public static final int PHOTOZOOM = 2; // 缩放
	public static final int PHOTORESOULT = 3;// 结果
	public static final String IMAGE_UNSPECIFIED = "image/*";

	private List<AreaInfo> mAreas = new ArrayList<AreaInfo>();

	private Handler handler = new Handler() {

		@Override
		public void handleMessage(Message msg) {
			try {
				String description = (String) msg.obj;
				switch (msg.what) {
				case UserTruckRequest.ADD_TRUCK_SUCCESSED:
					ProgressDialogHelper.dismiss();
					ToastHelper.toastShort(mContext, description);
					new Timer().schedule(new TimerTask() {

						@Override
						public void run() {
							setResult(888);
							finish();
						}
					}, 1000);
					break;
				case LHttpRequest.REQUEST_FAILED:
					ProgressDialogHelper.dismiss();
					ToastHelper.toastShort(mContext, description);
					break;
				default:
					break;
				}
			} catch (Exception e) {
				e.printStackTrace();
			}
			super.handleMessage(msg);
		}

	};

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		// tvTitle.setText(getResources().getString(R.string.add_truck));
		setContentView(R.layout.activity_add_social_truck);
		btnPCode = (Button) findViewById(R.id.btn_province_code);
		etTruckNum = (EditText) findViewById(R.id.et_truck_num);
		etTruckNum.setTransformationMethod(new AllCapTransfMethod());
		btnTruckType = (Button) findViewById(R.id.btn_truck_type);
		etTruckLoad = (EditText) findViewById(R.id.et_truck_load);
		btnTruckLength = (Button) findViewById(R.id.btn_truck_leng);
		btnDirect = (Button) findViewById(R.id.btn_truck_direction);
		btnSave = (Button) findViewById(R.id.btn_save);
		tvTruckPicSample = (TextView) findViewById(R.id.tv_truck_image);

		etTruckPhone = (EditText) findViewById(R.id.et_truck_phone);

		ivFull = (ImageView) findViewById(R.id.iv_car_full);
		tvTruckPicSample.setVisibility(View.VISIBLE);

		tvTruckPicSample.setOnClickListener(this);
		btnPCode.setOnClickListener(this);
		btnTruckType.setOnClickListener(this);
		btnTruckLength.setOnClickListener(this);
		btnDirect.setOnClickListener(this);
		ivFull.setOnClickListener(this);
		btnSave.setOnClickListener(this);
	}

	@Override
	public void onClick(View v) {
		Intent start;
		switch (v.getId()) {
		case R.id.btn_province_code:
			DialogChoiceTruckInfo choiceTruckNum = new DialogChoiceTruckInfo(
					mContext, "选择车牌", AttrUtil.TYPE_PROVINCE_SHORT,
					new DialogChoiceTruckInfo.OnChoiceListener() {

						@Override
						public void selected(AttributeInfo info) {
							try {
								btnPCode.setText(info.getName());
							} catch (Exception e) {
								e.printStackTrace();
							}
						}
					});
			choiceTruckNum.show();
			break;
		case R.id.iv_car_full:
			flag = 0;
			PictureUtil.doPickPhotoAction(this);
			break;
		case R.id.btn_truck_type:
			DialogChoiceTruckInfo choiceTruckType = new DialogChoiceTruckInfo(
					mContext, "选择车辆类型", AttrUtil.TYPE_TRUCK,
					new DialogChoiceTruckInfo.OnChoiceListener() {

						@Override
						public void selected(AttributeInfo info) {
							try {
								btnTruckType.setText(info.getName());
								pType = info.getCode();
							} catch (Exception e) {
								e.printStackTrace();
							}
						}
					});
			choiceTruckType.show();
			break;
		case R.id.btn_truck_leng:
			DialogChoiceLength length = new DialogChoiceLength(mContext,
					"选择车辆长度", new DialogChoiceLength.OnSelectListener() {

						@Override
						public void selected(AttributeInfo info) {
							try {
								btnTruckLength.setText(info.getCode());
							} catch (Exception e) {
								e.printStackTrace();
							}
						}
					});
			length.show();
			break;
		case R.id.btn_truck_direction:
			start = new Intent(mContext, ChoiceAreaActivity.class);
			start.putExtra("title", "期望流向(最多四个)");
			start.putExtra("is_mul", true);
			start.putExtra("max", 4);
			start.putExtra("type", true);
			start.putExtra("country", false);
			startActivityForResult(start, 502);
			break;
		case R.id.btn_save:
			saveTruckInfo();
			break;
		case R.id.tv_truck_image:
			// DialogPicSample dialogPicSample=new DialogPicSample(mContext,
			// R.drawable.truck_pic_sample);
			// dialogPicSample.show();
			break;
		case R.id.tv_travel_image:
			// DialogPicSample dialogPicSample1=new DialogPicSample(mContext,
			// R.drawable.travel_pic_sample);
			// dialogPicSample1.show();
			break;
		default:
			break;
		}

	}

	private void saveTruckInfo() {
		try {
			String pCode = btnPCode.getText().toString().trim();
			String truckNum = etTruckNum.getText().toString().trim();
			String truckPhone = etTruckPhone.getText().toString().trim();
			if (StringUtil.isNull(truckNum)) {
				ToastHelper.toastShort(mContext, "请输入车牌号码");
				return;
			}
			if (!StringUtil.isTruckNum(pCode + truckNum)) {
				ToastHelper.toastShort(mContext, "请输入正确的车牌号码");
				return;
			}

			if (mPTruckInfo == null) {
				ToastHelper.toastShort(mContext, "请进行车辆拍照！");
				return;
			}

			if (StringUtil.isNull(truckPhone)) {
				ToastHelper.toastShort(mContext, "请输入车辆电话");
				return;
			}

			if (!StringUtil.isMobileNO(truckPhone)) {
				ToastHelper.toastShort(mContext, "请输入正确的手机号");
				return;
			}

			if (truckDao.checkExistByPhone(truckPhone)) {
				ToastHelper.toastShort(mContext, "该手机号已经存在，请检查是否正确！");
				return;
			}

			String truckType = btnTruckType.getText().toString();
			if (StringUtil.isNull(truckType)) {
				ToastHelper.toastShort(mContext, "请选择车辆类型");
				return;
			}
			String weight = etTruckLoad.getText().toString();
			if (StringUtil.isNull(weight)) {
				ToastHelper.toastShort(mContext, "请填写车辆载重");
				return;
			}
			if (weight.equals("0") || weight.equals("0.0")) {
				ToastHelper.toastShort(mContext, "车辆载重不能为0");
				return;
			}
			String length = btnTruckLength.getText().toString();
			if (StringUtil.isNull(length)) {
				ToastHelper.toastShort(mContext, "请填写车辆长度");
				return;
			}
			if (length.equals("0") || length.equals("0.0")) {
				ToastHelper.toastShort(mContext, "车辆载重不能为0");
				return;
			}
			// String directStr = "";
			// String directCode = "";

			TruckInfo info = new TruckInfo();
			info.truckPlateNumber = pCode + truckNum;
			info.truckerPhone = truckPhone;
			if (mPTruckInfo != null) {
				info.truckPic = mPTruckInfo.getFilename();
			}
			info.truckTypeCode = Integer.parseInt(pType);
			info.truckType = btnTruckType.getText().toString();
			info.truckCapacity = etTruckLoad.getText().toString().trim();
			info.truckLength = btnTruckLength.getText().toString().trim();
			info.truckUpdateTime = DateUtils.formateDateTimeString(new Date());

			if (mAreas.size() > 0) {
				info.truckForwardCity1 = mAreas.get(0).getName();
				info.truckForwardCity1Code = Integer.valueOf(mAreas.get(0)
						.getCode());
			}
			if (mAreas.size() > 1) {
				info.truckForwardCity2 = mAreas.get(1).getName();
				info.truckForwardCity2Code = Integer.valueOf(mAreas.get(1)
						.getCode());
			}
			if (mAreas.size() > 2) {
				info.truckForwardCity3 = mAreas.get(2).getName();
				info.truckForwardCity3Code = Integer.valueOf(mAreas.get(2)
						.getCode());
			}
			if (mAreas.size() > 3) {
				info.truckForwardCity4 = mAreas.get(3).getName();
				info.truckForwardCity4Code = Integer.valueOf(mAreas.get(3)
						.getCode());
			}

			// mPictures.clear();
			// if(mPTruckInfo != null){
			// mPictures.add(mPTruckInfo);
			// }
			// String json = JsonUtil.toJson(mPictures);
			ToastHelper.toastShort(mContext, "正在保存数据,请稍后...");
			// new UserTruckRequest(mContext, handler).addTruck(pCode +
			// truckNum, pType, etTruckLoad.getText().toString(),
			// btnTruckLength.getText().toString(), directStr, directCode,
			// TruckInfo.TruckStatus.WAIT_SUBMIT,json);、
			if (truckDao.insert(info) > 0) {
				ToastHelper.toastShort(mContext, "车辆信息保存成功!");
				finish();
			}
		} catch (Exception e) {
			e.printStackTrace();
		}
	}

	@Override
	protected void onActivityResult(int requestCode, int resultCode, Intent data) {
		if (resultCode == RESULT_OK) {
			try {
				Intent intent = new Intent("com.android.camera.action.CROP");
				Uri data2 = null;
				if (data == null) {
					data2 = PictureUtil.getImageUri();
				} else {
					data2 = data.getData();
				}
				switch (requestCode) {
				case PictureUtil.PHOTO_PICKED_WITH_DATA:
					intent.setDataAndType(data2, "image/*");
					intent.putExtra("crop", true);
					// 设置裁剪尺寸
					intent.putExtra("aspectX", 1);
					intent.putExtra("aspectY", 1.5);
					intent.putExtra("outputX", 250);
					intent.putExtra("outputY", 375);
					intent.putExtra("return-data", true);
					intent.putExtra(MediaStore.EXTRA_OUTPUT,
							PictureUtil.getImageCaiUri());
					startActivityForResult(intent, PictureUtil.PHOTO_CROP);
					break;
				case PictureUtil.CAMERA_WITH_DATA:
					data2 = PictureUtil.getCameraImageCaiUri();
					intent.setDataAndType(data2, "image/*");
					intent.putExtra("crop", true);
					intent.putExtra("aspectX", 1);
					intent.putExtra("aspectY", 1.5);
					intent.putExtra("outputX", 250);
					intent.putExtra("outputY", 375);
					intent.putExtra("return-data", true);
					intent.putExtra(MediaStore.EXTRA_OUTPUT,
							PictureUtil.getImageCaiUri());
					startActivityForResult(intent, PictureUtil.PHOTO_CROP);
					break;
				case PictureUtil.PHOTO_CROP:
					Bundle bundle = data.getExtras();
					Bitmap myBitmap = (Bitmap) bundle.get("data");
					File file = Base64Util.saveBitmapToFile(myBitmap);
					PictureInfo info = new PictureInfo();
					info.setFileBase64Body(Base64Util.encodeImage(myBitmap));
					info.setFilename(file.getAbsolutePath());
					myBitmap.recycle();
					// info.setFilename(PictureUtil.getCharacterAndNumber() +
					// ".png");
					if (flag == 0) {
						info.setType(PictureInfo.FileType.truck);
						mPTruckInfo = info;
						ImageLoader.getInstance().displayImage(
								"file://" + file.getAbsolutePath(), ivFull,
								LImageLoader.mOptions);
					}
					break;
				default:
					break;
				}
			} catch (Exception e) {
				e.printStackTrace();
			}
		} else if (requestCode == 502) {
			if (data != null) {
				try {
					String json = data.getStringExtra("json");
					List<AreaInfo> areas = JsonUtil.getList(json,
							AreaInfo.class);
					mAreas.clear();
					mAreas.addAll(areas);
					if (areas.size() > 0) {
						String selected = "";
						for (AreaInfo info : areas) {
							selected = selected + info.getName() + ",";
						}
						btnDirect.setText(selected.substring(0,
								selected.length() - 1));
					}
				} catch (Exception e) {
					e.printStackTrace();
				}
			}
		}
		super.onActivityResult(requestCode, resultCode, data);
	}

	public void startPhotoZoom(Uri uri) {
		try {
			Intent intent = new Intent("com.android.camera.action.CROP");
			intent.setDataAndType(uri, IMAGE_UNSPECIFIED);
			intent.putExtra("crop", "true");
			// aspectX aspectY 是宽高的比例
			intent.putExtra("aspectX", 1);
			intent.putExtra("aspectY", 1.5);
			// outputX outputY 是裁剪图片宽高
			intent.putExtra("outputX", 400);
			intent.putExtra("outputY", 600);
			intent.putExtra("return-data", true);
			startActivityForResult(intent, PHOTORESOULT);
		} catch (Exception e) {
			e.printStackTrace();
		}
	}

	@Override
	public boolean onCreateOptionsMenu(Menu menu) {
		getSupportMenuInflater().inflate(R.menu.menu_confirm, menu);
		menu.getItem(0).setTitle("保存");
		return true;
	}

	@Override
	public boolean onOptionsItemSelected(MenuItem item) {
		switch (item.getItemId()) {
		case R.id.menu_confirm:
			saveTruckInfo();
			break;

		default:
			break;
		}
		return super.onOptionsItemSelected(item);
	}

}
